package org.rcy.framework.thrift.metadata;

import org.rcy.framework.thrift.log.RpcLog;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

public class MethodMetaData {
	
	private final String methodName;
	// 元数据
	private final SortedMap<FieldIdEnum, FieldMetaData> paramsMetaMap = new TreeMap();
	
	private static ConcurrentHashMap<String,MethodMetaData> cache = new ConcurrentHashMap();

	private MethodMetaData(Method method) {
		this.methodName = method.getName();
		
		Parameter[] parameters = method.getParameters();
		// 处理参数
		short index = 1;// 参数序号从1开始
		for (Parameter parameter : parameters) {
			String name = parameter.getName();
			FieldIdEnum field = new FieldIdEnum(index, name);
			
			Type type = parameter.getParameterizedType();
			FieldMetaData metaData = MetaDataBuilder.fieldMetaData(field, type,null);
			paramsMetaMap.put(field, metaData);
			index++;
		}
		
		FieldIdEnum logField = new FieldIdEnum(index, RpcLog.FIELD_NAME);
		FieldMetaData metaData = MetaDataBuilder.fieldMetaData(logField, RpcLog.class,null);
		paramsMetaMap.put(logField, metaData);  
	}
	
	public static synchronized MethodMetaData resolveMetaData(Method method){
		String methodKey = method.toString();
		MethodMetaData cacheMeta = cache.get(methodKey);
		if(cacheMeta!= null){
			return cacheMeta;
		}
		
		MethodMetaData metaData = new MethodMetaData(method);
		cache.put(methodKey, metaData);
		return metaData;
	}

	public String getMethodName() {
		return methodName;
	}

	public SortedMap<FieldIdEnum, FieldMetaData> getParamsMetaMap() {
		return paramsMetaMap;
	}

}
